package com.hkc.huakang.hkcpaperless;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.hkc.huakang.hkcpaperless.bin.DrugInfo;
import com.hkc.huakang.hkcpaperless.bin.LoggedInUser;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ScanTrigActivity extends AppCompatActivity{
    TextView   tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_scan_trig);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        tv=(TextView)findViewById(R.id.show_View);
        IntentFilter mFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context,"kalal",Toast.LENGTH_SHORT).show();

                //扫描结果的字符串数据
                final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
                final String scanResult_2 = intent.getStringExtra("SCAN_BARCODE2");
                //扫描结果的原始字节数据
                final byte[] scanResultByte_1 = intent.getByteArrayExtra("scan_result_one_bytes");
                final byte[] scanResultByte_2 = intent.getByteArrayExtra("scan_result_two_bytes");
                final int barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE", -1); // -1:unknown
                final String scanStatus = intent.getStringExtra("SCAN_STATE");
                if ("ok".equals(scanStatus)) {
                    //成功
                    getSuperVersionCode(scanResult_1);
                } else {
                    //失败如超时等
                }
            }
        };
        ScanTrigActivity.this.registerReceiver(mReceiver,mFilter);

    }
    public MysqlConnectResult<LoggedInUser> getSuperVersionCode(String  idCode){
        String newCode=idCode.substring(0,8);
        final Exception[] ep = new Exception[1];
        final LoggedInUser[] loggedInUser = {new LoggedInUser()};
        try {
            final CountDownLatch latch = new CountDownLatch(1); // 使用 CountDownLatch 来等待回调完成
            MysqlConnectUtil  mysqlConnectUtil=new   MysqlConnectUtil();
            mysqlConnectUtil.connect(new MysqlConnectUtil.ConnectResult() {
                @Override
                public void onConnectFail(Exception e) {
                    System.out.println("连接失败！");
                    latch.countDown();
                    ep[0] =e;
                }
                @Override
                public void onConnectSuccess() {
                 String  sql="SELECT *  from  drug_info WHERE  supervision_code LIKE '%"+newCode+"%'";
                    List<DrugInfo> list = mysqlConnectUtil.getSuperVersionCode(sql);
                    if(list!=null){
                        for (int i = 0; i < list.size(); i++) {
                           String rs= "药品名称："+list.get(i).getDrug_name()+"\n";
                           rs+="药品规格："+list.get(i).getDrug_spec()+"\n";
                           rs+="药品厂家："+list.get(i).getManufactory()+"\n";
                           rs+="监管码："+list.get(i).getSupervisson_code()+"\n";
                            tv.setText(rs);
                        }
                    }

                    //获取现在指针指向的行号，即为resultSet集合中数据的总行数
                    latch.countDown();

                }
            },this);
            latch.await(); // 阻塞等待
            if(ep[0]!=null) {
                return new MysqlConnectResult.Error(ep[0]);
            }else if(loggedInUser[0].getDisplayName()==null||loggedInUser[0].getDisplayName().isEmpty()){
                return new MysqlConnectResult.Error(new IOException("Error logging in" ));
            }
            return new MysqlConnectResult.Success<>(loggedInUser[0]);
        } catch (Exception e) {
            return new MysqlConnectResult.Error(new IOException("Error logging in", e));
        }
    }
}